<?php
define('ADMIN', '1'); //后台

require('global.php');
start();
$tplpath = 'admin';
$logfile = D_P.'data/cache/admin_record.php';
$admin_file = $_SERVER['PHP_SELF'];

/* 授权检验 */
$hardwareId = md5(getProcessorId());
$licensInfo = checkLicense($hardwareId);

/* 后台的登录权限判断 */
$login_fail=array();
$login_fail=F_L_count($logfile, 2000);
$L_left=9-$login_fail['count_F'];
$L_T = $login_fail['L_T']+1200-$timestamp;
if ($L_left<0 && $L_T>0)
{
	Cookie('login','',0);
	showmsg('login_fail');
}
list($login_name, $login_password) = explode("\t", GetCookie('login'));

if (!$login_name || $adminjob=='login')
{
	require(R_P.'admin/login.php');
	adminbottom();
}
$admindb = checkAdmin($login_name,$login_password);
$admin_uid = $admindb['uid'];

//根据权限生成菜单
require GetLang('menus');
$menu_father = array();
$menu_child = array();
$menu_allow = array('home','top','left','main','tree'); //初始化的几个操作，框架以及其框架页面
foreach ($menus as $key=>$menu)
{
	$menu_father[$key]=$menu['root'];
	$menu_child[$key]=array();
	foreach ($menu as $k=>$v){
		if($k=='root'){
			continue;
		}
		elseif ((strpos($k, 'set_') === 0) && $login_name!=$manager) //创始人才可以进行系统管理
		{
			//}elseif (($k == 'set_admin' || $k == 'set_creator') && $login_name!=$manager){
			continue;
		}
		else
		{
			//}elseif(in_array($k,$admindb['priv']) || $login_name==$manager){ //创始人拥有所有权限
			$menu_child[$key][$k]=$v;
			$menu_allow[]=$k;
		}
	}
	if(count($menu_child[$key])==0){
		unset($menu_father[$key]);
		unset($menu_child[$key]);
	}
}

//write log
if(!in_array($adminjob,array('top','left','main')))
{
	$new_record  = '';
	$_postdata	 = $_POST ? PostLog($_POST) : '';
	$record_name = str_replace('|','&#124;',Char_cv($login_name));
	$record_URI	 = str_replace('|','&#124;',Char_cv($REQUEST_URI));
	$new_record = "<?die;?>|$record_name||$record_URI|$onlineip|$timestamp|$_postdata|\n";
	writeover($logfile,$new_record,"ab");
}

require_once(R_P . 'admin/admincontrol.php');

if(empty($adminjob))
{
	require PrintEot('header');
	require PrintEot('frame');
	adminbottom(0);
}
elseif($adminjob=='left')
{
	require PrintEot('header');
	require PrintEot('left');
	adminbottom(0);
}
elseif ($adminjob=='top')
{
	require PrintEot('header');
	require PrintEot('top');
	adminbottom(0);
}
else
{
(strpos($adminjob,'.') || strpos($adminjob,'/')) && Showmsg("bad_request");
$basename = $admin_file."?adminjob=$adminjob";
!file_exists(R_P."admin/$adminjob.php") && Showmsg('undefined_action');
!in_array($adminjob,$menu_allow) && Showmsg('privilege');
require(R_P."admin/$adminjob.php");
}


function adminbottom($display=1)
{
	global $adminjob,$wind_version, $wind_repair, $db,$timestamp,$P_S_T,$very;
	$qn=$GLOBALS['queryNum'];
	$ft_gzip=($very['obstart']==1 ? "Gzip enabled" : "Gzip disabled");
	$t_array	= explode(' ',microtime());
	$totaltime	= number_format(($t_array[0]+$t_array[1]-$P_S_T),6);
	$wind_spend	= "Total $totaltime(s) query $qn ";
	if($display==1) require PrintEot('footer');
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
	ob_end_clean();
	$very['obstart'] == 1 && function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();
	echo $output;
	flush;
	exit;
}

function checkAdmin($login_name,$login_password)
{
	global $db,$manager,$manager_pwd,$timestamp,$logfile;
	if($GLOBALS['very']['cktime']){
		$GLOBALS['very']['cktime']<5 && $GLOBALS['very']['cktime']=5; //必须保证5分钟的有效时间
		$cktime = $GLOBALS['very']['cktime']*60;
	}else{
		$cktime = 1800;
	}
	$ck_time = $timestamp + $cktime;
	//Cookie('login',$login_name."\t".$login_password,$ck_time); //更新活动时间
	if($login_name==$manager && $login_password==$manager_pwd) //判断是创始人身份
	{
		return;
	}
	elseif($login_name)
	{
		$men = $db->get_one("SELECT * FROM cms_user WHERE username='$login_name' AND password='$login_password' LIMIT 1"); //判断是否管理员身份
		if($men)
		{
			if ($men['ifadmin'])
			{
				return ;
			}
			else
			{
				ObHeader('index.php');
				//adminmsg('您无权进行管理操作', 'index.php');
			}
			//$men['priv'] = explode(',',$men['priv']);
			//return $men;
			return ;
		}
		else
		{
			$record_name= str_replace('|','&#124;',Char_cv($login_name));
			$record_pwd	= str_replace('|','&#124;',Char_cv($login_password));
			$new_record="<?die;?>|$record_name|$record_pwd|Logging Failed|$onlineip|$timestamp|\n";
			writeover($logfile,$new_record,"ab");
		}
	}
	Cookie('login','',0);
	showmsg('login_invalidation');
}

function adminmsg($msg,$jumpurl='',$t=2)
{
	require PrintEot('header');
	extract($GLOBALS, EXTR_SKIP);
	!$basename && $basename=$REQUEST_URI;
	!$jumpurl && $jumpurl=$basename;
	$ifjump="<META HTTP-EQUIV='Refresh' CONTENT='$t; URL=$jumpurl'>";
	require_once GetLang('cpmsg');
	$lang[$msg] && $msg=$lang[$msg];
	$outmsg="<div style='font-size:12px;font-family:verdana;line-height:180%;color:#666;border:dashed 1px #ccc;padding:1px;margin:20px;'>";
	$outmsg.="<div style=\"background: #eeedea;padding-left:10px;font-weight:bold;height:25px;\">$lang[prompt]</div>";
	$outmsg.="<div style='padding:20px;font-size:14px;'><img src='images/admin/ok.gif' align='absmiddle' hspace=20 ><span>$msg</span></div>";
	$outmsg.="<div style=\"text-align:center;height:30px;\">$ifjump<a href=\"$jumpurl\">$lang[back]</a></div>";
	$outmsg.="</div>";
	echo $outmsg;
	adminbottom();
}

function operate($msg,$jumpurl='',$t=2)
{
	require PrintEot('header');
	extract($GLOBALS, EXTR_SKIP);
	!$basename && $basename=$REQUEST_URI;
	!$jumpurl && $jumpurl=$basename;
	$ifjump="<META HTTP-EQUIV='Refresh' CONTENT='$t; URL=$jumpurl'>";
	require_once GetLang('cpmsg');
	$lang[$msg] && $msg=$lang[$msg];
	$outmsg="<div style='font-size:12px;font-family:verdana;line-height:180%;color:#666;border:dashed 1px #ccc;padding:1px;margin:20px;'>";
	$outmsg.="<div style=\"background: #eeedea;padding-left:10px;font-weight:bold;height:25px;\">$lang[prompt]</div>";
	$outmsg.="<div style='padding:20px;font-size:14px;'><img src='images/admin/ok.gif' align='absmiddle' hspace=20 ><span>$msg</span></div>";
	$outmsg.="<div style=\"text-align:center;height:30px;\">$ifjump<a href=\"$basename\">$lang[back]</a></div>";
	$outmsg.="</div>";
	$outmsg.="<script language=\"javascript\">\n
	var left = parent.leftFrame;\n
	left.location.reload();\n
	</script>\n
	";
	echo $outmsg;
	adminbottom();
}


function readlog($filename,$offset=1024000){
	$readb=array();
	if($fp=@fopen($filename,"rb")){
		flock($fp,LOCK_SH);
		$size=filesize($filename);
		$size>$offset ? fseek($fp,-$offset,SEEK_END): $offset=$size;
		$readb=fread($fp,$offset);
		fclose($fp);
		$readb=str_replace("\n","\n<:wind:>",$readb);
		$readb=explode("<:wind:>",$readb);
		$count=count($readb);
		if($readb[$count-1]==''||$readb[$count-1]=="\r"){unset($readb[$count-1]);}
		if(empty($readb)){$readb[0]="";}
	}
	return $readb;
}

function PostLog($log){
	foreach($log as $key=>$val){
		if(is_array($val)){
			$data .= "$key=array(".PostLog($val).")";
		}else{
			$val = str_replace(array("\n","\r","|"),array('','','&#124;'),$val);
			if($key=='password' || $key=='check_pwd'){
				$data .= "$key=***, ";
			}else{
				$data .= "$key=$val, ";
			}
		}
	}
	return $data;
}

function EncodeUrl($url){
	global $very,$login_name,$admin_uid;
	$url_a=substr($url,strrpos($url,'?')+1);
	substr($url,-1)=='&' && $url=substr($url,0,-1);
	parse_str($url_a,$url_a);
	$source='';
	foreach($url_a as $key=>$val){
		$source .= $key.$val;
	}
	$posthash=substr(md5($source.$login_name.$admin_uid.$very['hash']),0,8);
	$url .= "&verify=$posthash";
	return $url;
}

function PostCheck($verify){
	global $very,$login_name,$admin_uid;
	$source='';
	foreach($_GET as $key=>$val){
		if($key!='verify'){
			$source .= $key.$val;
		}
	}
	if($verify!=substr(md5($source.$login_name.$admin_uid.$very['hash']),0,8)){
		adminmsg('bad_request');
	}else{
		return true;
	}
}

function checkselid($selid){
	if(is_array($selid)){
		$ret='';
		foreach($selid as $key => $value){
			if(!is_numeric($value)){
				return false;
			}
			$ret .= $ret ? ','.$value : $value;
		}
		return $ret;
	} else{
		return '';
	}
}

/**
 * 后台连续登陆错误次数
 *
 * @param string $filename  日志文件
 * @param string $offset    记录字节数
 * @return array $result    count_F:错误次数  L_T:最后登陆错误时间
 */
function F_L_count($filename,$offset){
	global $onlineip,$timestamp;
	$result=array();
	if($fp=@fopen($filename,"rb")){
		flock($fp,LOCK_SH);
		fseek($fp,-$offset,SEEK_END);
		$readb=fread($fp,$offset);
		fclose($fp);
		$readb=trim($readb);
		$readb=explode("\n",$readb);
		$count=count($readb);
		$tmp=array();
		for($i=$count-1;$i>0;$i--){
			$tmp=explode("|",$readb[$i]);
			if(strpos($readb[$i],"|Logging Failed|$onlineip|")===false){
				continue;
			}elseif($result['count_F']>=10 || $tmp['5']<$timestamp-1200){
				break;
			}
			$result['count_F']++;
			$result['L_T'] < $tmp['5'] && $result['L_T'] = $tmp['5'];
		}
	}
	return $result;
}

/**
 * 获取CPUID，用于授权验证
 *
 * @return string
 */
function getProcessorId()
{
	$objLocator = new COM("WbemScripting.SWbemLocator");
	$wmi = $objLocator->ConnectServer();
	$prop = $wmi->get("Win32_PnPEntity");
	//CPU
	$cpuinfo = GetWMI($wmi,"Win32_Processor", array('ProcessorId'));
	//print_r($cpuinfo);
	return $cpuinfo[0]['ProcessorId'];
}

function GetWMI($wmi,$strClass, $strValue = array()) {
	$arrData = array();

	$objWEBM = $wmi->Get($strClass);
	$arrProp = $objWEBM->Properties_;
	$arrWEBMCol = $objWEBM->Instances_();
	foreach($arrWEBMCol as $objItem) {
		@reset($arrProp);
		$arrInstance = array();
		foreach ($arrProp as $propItem) {
			eval("\$value = \$objItem->" . $propItem->Name . ";");
			if (empty($strValue)) {
				$arrInstance[$propItem->Name] = trim($value);
			} else {
				if (in_array($propItem->Name, $strValue)) {
					$arrInstance[$propItem->Name] = trim($value);
				}
			}
		}
		$arrData[] = $arrInstance;
	}
	return $arrData;
}

/**
 * 检验License是否合法
 *
 */
function checkLicense($hardwareId)
{
	if (!file_exists(D_P . 'data/license.txt'))
	{
		Showmsg('不存在授权文件，程序被迫中止，请联系北京曙光计算机公司，您的授权ID是：' . $hardwareId);
	}
	$fileContent = readover(D_P . 'data/license.txt');
	$decode = ereg_replace("([a-z]){1}", "|", $fileContent);
	$strArr = explode("|", $decode);
	$licensInfo = array();
	$licensInfo['type'] = getDecodeVal($strArr,0, 1);
	$licensInfo['invalid'] = getDecodeVal($strArr, 1, 8);
	$licensInfo['hardwareid'] = getDecodeVal($strArr, 9, 32);
	$licensInfo['client'] = urldecode(getDecodeVal($strArr, 41));

	if (intval($licensInfo['invalid']) == 0) $licensInfo['invalid'] = '永不过期';
	if ($hardwareId != $licensInfo['hardwareid'])
	{
		Showmsg('硬件ID不匹配，此服务器未被授权使用本系统');
	}
	return $licensInfo;
}

function getDecodeVal($strArr, $start, $len = 0)
{
	$returnVal = '';
	if ($len == 0) $len = count($strArr);
	for ($i = $start; $i < $start+$len; $i++)
	{
		if (empty($strArr[$i])) continue;
		$val = chr(hexdec($strArr[$i]));
		$returnVal .= $val;
	}
	return $returnVal;
}
?>